import { adminMoneyUnitGetAPI } from '@/api/common'

/**
 * 金额单位
 */
const unit = {
  state: {
    // 0：元、1：万元
    unit: {
      crm: 0,
      oa: 0,
      hrm: 0,
      jxc: 0
    }
  },

  mutations: {
    /**
     * 设置各模块单位标识
     */
    SET_UNIT: (state, allModule) => {
      const {
        crm = 0,
        oa = 0,
        hrm = 0,
        jxc = 0
      } = allModule

      state.unit.crm = crm
      state.unit.oa = oa
      state.unit.hrm = hrm
      state.unit.jxc = jxc
    }

  },

  actions: {
    // 登录
    GetMoneyUnit({
      state,
      commit
    }) {
      return new Promise((resolve, reject) => {
        adminMoneyUnitGetAPI()
          .then(response => {
            const unitObj = {}
            const moduleUnitMap = {
              1: 'crm',
              2: 'oa',
              3: 'jxc',
              4: 'hrm'
            }
            const data = response.data || []
            for (const item of data) {
              unitObj[moduleUnitMap[item.label]] = item.unit
            }
            commit('SET_UNIT', unitObj)
            resolve(response)
          })
          .catch(error => {
            commit('SET_UNIT', {})
            reject(error)
          })
      })
    }

  },

  getters: {
    unit: state => state.unit
  }
}

export default unit
